package com.klcw.distributedCommunication.serialization.parent;

import java.io.*;

/**
 * @ClassName SerializeDemo
 * @Description 序列化
 * @Author dukang
 * @Date 2019/1/22 10:48
 * @Version 1.0
 **/
public class SuperSerializeDemo {

    public static void main(String[] args) {
        SerializePerson();

        User persons = DeSerializePerson();
        System.out.println(persons);
    }

    // 序列化操作
    private static void SerializePerson(){
        try {
            ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream(new File("persons")));
            User persons = new User();
            persons.setAge(16);
            persons.setName("dukang");
            stream.writeObject(persons);
            stream.flush();   //刷新缓存;

            // 读取person ， 判断两个对象是否相等
            ObjectInputStream persons1 = new ObjectInputStream(new FileInputStream(new File("persons")));
            User p1 = (User)persons1.readObject();

            persons.setAge(16);
            persons.setName("xiaoren");
            stream.writeObject(persons);
            stream.flush();
            // 获取文件信息需要将文件包装成一个文件对象
            System.out.println("序列化成功" + new File("persons").length());
            User p2 = (User)persons1.readObject();
            System.out.println(p1==p2);  // 同一个对象，第二个之会保存引用，还会保存不一样的字段

            persons1.close();
            // 关闭流对象
            stream.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    // 反序列化
    public static User DeSerializePerson(){
        try {
            // 文件读入流对象
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("persons")));
            // 读取Object流对象
            User person = (User) ois.readObject();
            return person;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}
